import React, { useState } from "react";
import { Button, Input, Form } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Checkbox } from "react-vant";
import { CenterPopup } from "antd-mobile";
import axios from "axios";
import style from "./index.module.scss";
import { PhoneO } from "@react-vant/icons";
import { useAppDispatch } from "../../store/store";
import { setUserinfor } from "../../store/userSliceReducer";
export default () => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  //复选框状态
  const [checked, setChecked] = React.useState(false);
  //弹出框显示
  const [visible, setVisible] = useState(false);
  const onFinish = async (values: any) => {
    const { username, password } = values;
    //判断是否同意协议
    if (!checked) {
      setVisible(true);
      return;
    }
    const res = await axios.post("/api/login", {
      username,
      password,
    });
    console.log(res.data);
    const { code, msg, data } = res.data;
    if (code === 200) {
      alert(msg);
      dispatch(setUserinfor(data))
      console.log(data);
      navigate("/my");
    } else {
      alert("登录失败");
    }
  };
  //跳转到手机号登录
  const tz = () => {
    navigate("/phonelogin");
  };
  return (
    <div className={style.box}>
      <CenterPopup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
      >
        <div className={style.myContent}>请先阅读并同意《用户协议》 《隐私政策》</div>
      </CenterPopup>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              提交
            </Button>
            <div className={style.loginoptions}>
              <div>——————</div>
              <span>其它登录方式</span>
              <div>———————</div>
            </div>
            <div className={style.loginoption} onClick={() => tz()}>
              <div>
                <PhoneO />
              </div>
              <div>手机号登录</div>
            </div>
          </div>
        }
      >
        <Form.Item
          tooltip={{
            message:
              "A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
          }}
          intro="确保这是唯一的用户名"
          rules={[{ required: true, message: "请填写用户名" }]}
          name="username"
          label="用户名"
        >
          <Input placeholder="请输入用户名" className={style.inp} />
        </Form.Item>
        <Form.Item
          rules={[{ required: true, message: "请填写密码" }]}
          name="password"
          label="密码"
        >
          <Input placeholder="请输入密码" className={style.inp} />
        </Form.Item>
        <Form.Item>
          <Checkbox checked={checked} onChange={setChecked}>
            我已阅读并同意 《用户协议》 《隐私政策》
          </Checkbox>
        </Form.Item>
      </Form>
    </div>
  );
};